#import "SSAccessoryInfo.h"
#import <ExternalAccessory/ExternalAccessory.h>
#import <AVFoundation/AVFoundation.h>
@implementation SSAccessoryInfo
+ (BOOL)accessoriesAttached {
    @try {
        EAAccessoryManager *accessoryManager = [EAAccessoryManager sharedAccessoryManager];
        int numberOfAccessoriesConnected = (int)[accessoryManager.connectedAccessories count];
        if (numberOfAccessoriesConnected > 0) {
            return true;
        } else {
            return false;
        }
    }
    @catch (NSException *exception) {
        return false;
    }
}
+ (BOOL)headphonesAttached {
    @try {
        AVAudioSessionRouteDescription *route = [[AVAudioSession sharedInstance] currentRoute];
        for (AVAudioSessionPortDescription *desc in [route outputs]) {
            if ([[desc portType] isEqualToString:AVAudioSessionPortHeadphones]) {
                return YES;
            }
        }
        return NO;
    }
    @catch (NSException *exception) {
        return false;
    }
}
+ (NSInteger)numberAttachedAccessories {
    @try {
        EAAccessoryManager *accessoryManager = [EAAccessoryManager sharedAccessoryManager];
        int numberOfAccessoriesConnected = (int)[accessoryManager.connectedAccessories count];
        return numberOfAccessoriesConnected;
    }
    @catch (NSException *exception) {
        return false;
    }
}
+ (NSString *)nameAttachedAccessories {
    @try {
        EAAccessoryManager *accessoryManager = [EAAccessoryManager sharedAccessoryManager];
        EAAccessory *accessory;
        int numberOfAccessoriesConnected = (int)[accessoryManager.connectedAccessories count];
        if (numberOfAccessoriesConnected > 0) {
            NSString *allAccessoryNames = @"";
            NSString *accessoryName;
            NSArray *accessoryArray = accessoryManager.connectedAccessories;
            for (int x = 0; x < numberOfAccessoriesConnected; x++) {
                accessory = [accessoryArray objectAtIndex:x];
                accessoryName = [accessory name];
                if (accessoryName == nil || accessoryName.length == 0) {
                    accessoryName = [accessory manufacturer];
                }
                if (accessoryName == nil || accessoryName.length == 0) {
                    accessoryName = @"Unknown";
                }
                allAccessoryNames = [allAccessoryNames stringByAppendingFormat:@"%@", accessoryName];
                if (x < numberOfAccessoriesConnected - 1) {
                    allAccessoryNames = [allAccessoryNames stringByAppendingFormat:@", "];
                }
            }
            return allAccessoryNames;
        } else {
            return nil;
        }
    }
    @catch (NSException *exception) {
        return nil;
    }
}
@end
